package com.tmt.paymentcenter.web.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

@Getter
@Setter
public class HttpResult implements Serializable {

	/** 编码，默认为0，表示成功，其他表示失败，特定标示对应特定意义 */
	private int code = 0;
	private ResultType type;
	private String message;
	private String url;
	private Object data;

	public boolean isSuccess() {
		return code == 0;
	}

	public static HttpResult redirect(String url) {
		return redirect(url, null);
	}

	public static HttpResult redirect(String url, String message) {
		HttpResult result = new HttpResult();
		result.setType(ResultType.REDIRECT);
		result.setUrl(url);
		result.setMessage(message);

		return result;
	}

	public static HttpResult success() {
		return success(null, null);
	}

	public static HttpResult success(String message) {
		return success(message, null);
	}

	public static HttpResult success(String message, Object data) {
		HttpResult result = new HttpResult();
		result.setType(ResultType.SUCCESS);
		result.setMessage(message);
		result.setData(data);

		return result;
	}

	public static HttpResult failure() {
		return failure(null, null);
	}

	public static HttpResult failure(String message) {
		return failure(message, null);
	}

	public static HttpResult failure(String message, Object data) {
		return failure(1, message, data);
	}

	public static HttpResult failure(int code, String message, Object data) {
		HttpResult result = new HttpResult();
		result.setCode(code);
		result.setType(ResultType.FAILURE);
		result.setMessage(message);
		result.setData(data);

		return result;
	}

	public enum ResultType {
		FAILURE, SUCCESS, REDIRECT
	}

	public JSONObject toJSONObject(){
		try {
			ObjectMapper mapper = new ObjectMapper();
			String jsonInString = mapper.writeValueAsString(this);
			return JSON.parseObject(jsonInString);
		}catch (Exception ex){}
		return new JSONObject();
	}

	@Override
	public String toString() {
		return "HttpResult{" +
				"code=" + code +
				", type=" + type +
				", message='" + message + '\'' +
				", url='" + url + '\'' +
				", data=" + data +
				'}';
	}
}

